﻿using MediatR;
using SmartProduction.Domain.yjh;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.MaterList;

namespace SmartProduction.Read.API.Application.CommandHandlers.MaterList
{
    /// <summary>
    /// 物料查询命令处理
    /// </summary>
    public class MaterListQueryCommandHandler:IRequestHandler<MaterQueryListCommand,APIResult<APIPaing<MaterialList>> >
    {
        /// <summary>
        /// 物料仓储
        /// </summary>
        private readonly IBaseRepository<MaterialList> materep;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="materep">物料仓储</param>
        public MaterListQueryCommandHandler(IBaseRepository<MaterialList> materep)
        {
            this.materep = materep;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public async Task<APIResult<APIPaing<MaterialList>>> Handle(MaterQueryListCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaing<MaterialList>> result = new APIResult<APIPaing<MaterialList>>();

            var list = materep.GetAll().Result.Where(x => x.IsDeleted == false);

            if (!string.IsNullOrEmpty(request.MaterialCode))
            {
                list = list.Where(x => x.MaterialCode == request.MaterialCode);
            }
            if (!string.IsNullOrEmpty(request.MaterialVersion))
            {
                list = list.Where(x => x.MaterialVersion == request.MaterialVersion);
            }
            if (request.IsStatus!=null)
            {
                list = list.Where(x => x.IsStatus == request.IsStatus);
            }
            if (!string.IsNullOrEmpty(request.MaterialName))
            {
                list = list.Where(x => x.MaterialName == request.MaterialName);
            }

            int totalcount=list.Count();
            int totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.size);

            var pagelist = list.OrderByDescending(x => x.MaterialId).Skip((request.index - 1) * request.size).Take(request.size);


            APIPaing<MaterialList> page= new APIPaing<MaterialList>();  
            page.TotalCount = totalcount;
            page.PageCount = totalpage;
            page.Items = pagelist.ToList();

            result.data= page;

            return await Task.FromResult(result);
        }
    }
}
